package com.whatech.mall.gateway.filter;

import com.google.common.collect.Maps;
import com.whatech.mall.common.jwt.JwtOperator;
import com.whatech.mall.common.jwt.JwtProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 自定义GlobalFilter，为所有请求添加JWT Header。
 */
@Slf4j
@Component
public class AddJwtGlobalFilter implements GlobalFilter, Ordered {

    // 为微服务通信的JWT设置一个足够长的过期时间，比如1年
    private static final long MS_JWT_EXPIRATION_IN_SECOND = 31536000L;
    private static String[] msJwtTokens;

    @Autowired(required = false)
    private JwtProperties jwtProperties;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        if (jwtProperties == null
                || !jwtProperties.isMsJwtEnabled()
                || StringUtils.isEmpty(jwtProperties.getMsJwtHeader())) {
            return chain.filter(exchange);
        }
        // 为请求添加微服务间通信的JWT Header
        ServerHttpRequest modifiedRequest = exchange.getRequest()
                .mutate()
                .header(jwtProperties.getMsJwtHeader(), getMsJwtTokens(jwtProperties))
                .build();
        ServerWebExchange modifiedExchange = exchange.mutate()
                .request(modifiedRequest)
                .build();
        return chain.filter(modifiedExchange);
    }

    @Override
    public int getOrder() {
        return -1;
    }

    private static String[] getMsJwtTokens(final JwtProperties jwtProperties) {
        if (msJwtTokens == null) {
            synchronized (AddJwtGlobalFilter.class) {
                if (msJwtTokens == null) {
                    final JwtProperties copyJwtProperties = new JwtProperties();
                    BeanUtils.copyProperties(jwtProperties, copyJwtProperties);
                    copyJwtProperties.setExpirationInSecond(MS_JWT_EXPIRATION_IN_SECOND);
                    JwtOperator jwtOperator = new JwtOperator(copyJwtProperties);
                    msJwtTokens = new String[] {jwtOperator.generateToken(Maps.newHashMap())};
                }
            }
        }
        return msJwtTokens;
    }
}